__author__ = 'zoulida'

import queue
import threading
import time

#from retrying import retry
from random import randint






def tlimit(limit, *default):#装饰函数，limit是限时
    def wrapper(function):
        def proWarp(*args, **kwargs):
            result = queue.Queue()
            mutex = threading.Lock()
            mutex.acquire()
            def t_error() : mutex.release()
            def process(*args, **kwargs):
                result.put(function(*args, **kwargs))
                if mutex.locked() : mutex.release()
            timer = threading.Timer(limit, t_error)
            thread = threading.Thread(target = process,
                                      args = args, kwargs = kwargs)
            thread.setDaemon(True)
            timer.start()
            thread.start()
            if mutex.acquire():
                timer.cancel()
                if not result.empty():
                    return result.get()
                else:
                    if default:
                        return default[0]
                    raise TimeoutError
        return proWarp
    return wrapper

@tlimit(2)
def get_random():#这是个例子
    int_r = randint(0, 100)

    if int_r >= 0:
        print(f"该随机数等于{int_r}")
        #raise IOError("该随机数大于0")
    else:
        return int_r
    time.sleep(4)

if __name__ == '__main__':
    print(f"该随机数等于{get_random()}")
